
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
  RadialLinearScale,
  PointElement,
  LineElement,
  Filler
} from 'chart.js';
import { Bar, Radar } from 'react-chartjs-2';
import { WorkPatterns } from '../../services/insightsAPI';

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  RadialLinearScale,
  PointElement,
  LineElement,
  Filler,
  Title,
  Tooltip,
  Legend
);

interface WorkPatternsChartProps {
  data: WorkPatterns;
}

export default function WorkPatternsChart({ data }: WorkPatternsChartProps) {
  // 准备小时分布数据
  const hours = Array.from({ length: 24 }, (_, i) => i);
  const creationData = hours.map(hour => {
    const found = data.hourlyCreation.find(item => item.hour === hour);
    return found ? found.count : 0;
  });
  const completionData = hours.map(hour => {
    const found = data.hourlyCompletion.find(item => item.hour === hour);
    return found ? found.count : 0;
  });

  const hourlyChartData = {
    labels: hours.map(h => `${h}:00`),
    datasets: [
      {
        label: '任务创建',
        data: creationData,
        backgroundColor: 'rgba(59, 130, 246, 0.6)',
        borderColor: 'rgba(59, 130, 246, 1)',
        borderWidth: 1
      },
      {
        label: '任务完成',
        data: completionData,
        backgroundColor: 'rgba(34, 197, 94, 0.6)',
        borderColor: 'rgba(34, 197, 94, 1)',
        borderWidth: 1
      }
    ]
  };

  const hourlyChartOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        position: 'top' as const,
        labels: {
          font: {
            size: 12
          }
        }
      },
      title: {
        display: true,
        text: '24小时工作模式分布',
        font: {
          size: 14,
          weight: 'bold' as const
        }
      }
    },
    scales: {
      x: {
        grid: {
          display: false
        },
        ticks: {
          font: {
            size: 10
          },
          maxTicksLimit: 12
        }
      },
      y: {
        beginAtZero: true,
        grid: {
          color: 'rgba(0, 0, 0, 0.1)'
        },
        ticks: {
          font: {
            size: 10
          }
        }
      }
    }
  };

  // 准备雷达图数据（高效时段分析）
  const radarLabels = [
    '早晨 (6-9)',
    '上午 (9-12)',
    '中午 (12-15)',
    '下午 (15-18)',
    '晚上 (18-21)',
    '深夜 (21-24)'
  ];

  const getTimeSlotData = (timeSlot: [number, number]) => {
    const [start, end] = timeSlot;
    return completionData.slice(start, end).reduce((sum, val) => sum + val, 0);
  };

  const radarData = {
    labels: radarLabels,
    datasets: [
      {
        label: '任务完成数量',
        data: [
          getTimeSlotData([6, 9]),
          getTimeSlotData([9, 12]),
          getTimeSlotData([12, 15]),
          getTimeSlotData([15, 18]),
          getTimeSlotData([18, 21]),
          getTimeSlotData([21, 24])
        ],
        backgroundColor: 'rgba(168, 85, 247, 0.2)',
        borderColor: 'rgba(168, 85, 247, 1)',
        borderWidth: 2,
        pointBackgroundColor: 'rgba(168, 85, 247, 1)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: 'rgba(168, 85, 247, 1)'
      }
    ]
  };

  const radarOptions = {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        display: false
      },
      title: {
        display: true,
        text: '高效时段分析',
        font: {
          size: 14,
          weight: 'bold' as const
        }
      }
    },
    scales: {
      r: {
        beginAtZero: true,
        grid: {
          color: 'rgba(0, 0, 0, 0.1)'
        },
        pointLabels: {
          font: {
            size: 11
          }
        },
        ticks: {
          display: false
        }
      }
    }
  };

  return (
    <div className="space-y-6">
      {/* 24小时工作模式分布 */}
      <div className="bg-theme-bg rounded-xl border border-theme-border/60 shadow-sm p-5">
        <div style={{ height: '300px' }}>
          <Bar data={hourlyChartData} options={hourlyChartOptions} />
        </div>
      </div>

      {/* 统计卡片和雷达图 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
        {/* 效率统计卡片 */}
        <div className="bg-theme-bg rounded-xl border border-theme-border/60 shadow-sm p-5">
          <h3 className="text-sm font-semibold text-theme-text mb-4 flex items-center gap-2">
            <div className="w-1 h-4 bg-blue-500 rounded-full"></div>
            工作日 vs 周末效率
          </h3>
          
          <div className="space-y-3">
            {data.weekdayEfficiency.map((item, index) => (
              <div key={index} className="flex items-center justify-between p-3 bg-theme-bg-secondary rounded-lg">
                <div>
                  <span className="font-medium text-theme-text">
                    {item.dayType === 'weekday' ? '工作日' : '周末'}
                  </span>
                  <p className="text-sm text-theme-text-secondary">
                    完成任务: {item.completedCount} 个
                  </p>
                </div>
                <div className="text-right">
                  <span className="text-lg font-bold text-blue-600">
                    {item.avgCompletionDays || 'N/A'}
                  </span>
                  <p className="text-xs text-theme-text-muted">平均天数</p>
                </div>
              </div>
            ))}
          </div>

          {/* 高效时段 */}
          {data.peakHours.length > 0 && (
            <div className="mt-4 pt-4 border-t border-theme-border">
              <h4 className="text-sm font-medium text-theme-text mb-3">🏆 最高效时段</h4>
              <div className="space-y-2">
                {data.peakHours.slice(0, 3).map((hour, index) => (
                  <div key={index} className="flex items-center justify-between text-sm">
                    <span className="text-theme-text-secondary">
                      {hour.hour}:00 - {hour.hour + 1}:00
                    </span>
                    <span className="font-medium text-green-600">
                      {hour.completedCount} 个任务
                    </span>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* 高效时段雷达图 */}
        <div className="bg-theme-bg rounded-xl border border-theme-border/60 shadow-sm p-5">
          <div style={{ height: '280px' }}>
            <Radar data={radarData} options={radarOptions} />
          </div>
        </div>
      </div>
    </div>
  );
}
